<?php
/**
 * 会员相关
 *
 */
class member_model_data extends Model{
	/**
	 * 表名
	 */
	
	public function __construct(){
		parent::__construct();
		$this->table = 'train_members';
	}
	
	/**
	 * 注册信息
	 *
	 * @param unknown_type $args
	 */
	public function register($args){
		if(!($args['username'] && $args['pwd'] && $args['email'])) return false;
		$args['pwd'] = member_util_interface::genKey($args['username'],$args['pwd']);
		$args['reg_time']	=	CURRENT_TIME;
		$args['active_code'] = 	getRandom(16);
		if($uid = $this->db->insert($this->table,$args)){
			//发送激活邮件
//			member_util_interface::sendMail($args['email'],'激活邮件','激活邮件');
			return $uid;
		}
	}
	
	/**
	 * 编辑用户信息
	 *
	 * @param array $data
	 * @param int $uid
	 * @return int
	 */
	public function edit($data, $uid)
	{
		$uid = (int) $uid;
		if (!$uid) return false;
		
		$data['up_time'] = time();
		return $this->db->update($this->table, $data, array('uid' => $uid),'uid=&uid');
	}
	
	/**
	 * 激活用户
	 */
	public function active($act_code){
        /**
         * 验证数据是否符合要求
         */
        if(preg_match('/[\d\w]{16}/',$act_code)){
            return $this->db->query("UPDATE $this->table SET flag = 0 WHERE active_cod = $act_code AND flag = 0");
        }
        return false;
	}
	
	/**
	 * 修改个人头像
	 *
	 * @param unknown_type $uid
	 * @param unknown_type $headimg
	 * @return unknown
	 */
	public function up_headimg($uid,$headimg=1){
		if(!($uid && $headimg)) return false;
		if($this->db->query("UPDATE $this->table SET headimg = $headimg WHERE uid=".$uid)){
            $this->getUserByUid($uid,true);
            return true;
        }
        return false;
	}
	
	/**
	 * 用户登录
	 *
	 * @param string $username	用户名
	 * @param string $pwd	密码
	 */
	public function login($username,$pwd,$always=false){
		if(!($username && $pwd)) return false;
		$pwd = member_util_interface::genKey($username,$pwd);
		if($user = $this->db->fetchRow("SELECT * FROM $this->table WHERE username = '{$username}' AND pwd='{$pwd}'")){
			if($user['flag']==0){
				return ConstMembers::ERR_NOT_ACTIVE ;
			}
			member_util_login::makeCookie($user,$always);
			return array('uid'=>$user['uid'],'nickname'=>$user['username'],'email'=>$user['email'],'headimg'=>$user['headimg']);
		}
		return ConstMembers::ERR_INVALID_USER ;// 用户和密码错误
	}
	
	/**
	 * 找回密码
	 *
	 * @param unknown_type $key
	 */
	public function find_pwd($key){
		
	}
	
	/**
	 * 获取会员信息
	 *
	 * @param unknown_type $uid
	 * @return unknown
	 */
	public function getRrow($uid){
		if(!$uid) return false;
		return $this->db->fetchRow("SELECT * FROM $this->table WHERE uid= $uid ");
	}
	
	/**
	 * 搜索会员
	 * @param unknown_type $args
	 * @param int $page 页码
	 * @param int $pageSize 每页数量
	 */
	public function search($args = array('uid'=>'', 'username'=>'','email'=>''),$page = 1,$pageSize = 16,$exclude = false,$flag=true){
		$sql = "SELECT * FROM $this->table WHERE flag>0 ";
		if($flag === false){
			$sql = "SELECT * FROM $this->table WHERE 1 ";
		}
		if($args['username']){
			$sql.=" AND username LIKE '".$args['username']."%' ";
		}
		if($args['email']){
			$sql.=" AND username = '".$args['email']."' ";
		}
		if($args['uid']){
			$sql.=" AND uid = ".$args['uid']." ";
		}
		
		if($args['sex']){
			$sql.=" ADN sex = ".$args['sex'];
		}
		/**
		 * 排除的uid 
		 */
		if($exclude){
			$sql.=" AND uid NOT IN (".(is_array($exclude)?implode(',',$exclude):$exclude).")";
		}
		
		$sql.= " ORDER BY uid DESC ";
		
		return $this->db->selectPage($sql,array(),$page,$pageSize);
	}
	
	/**
	 * 根据uid获取用户信息
	 * Enter description here ...
	 * @param unknown_type $uid
	 */
	public function getUserByUid($uid,$flush = false){
		if(!is_numeric($uid)) return false;
		$key = USER_MEM_KEY.$uid;
		if(!($row = MemRow::getCache($key)) || $flush==true){
			$row = $this->getRrow($uid);
			$cnt = $this->getCountByUid($uid);
			$row['sub_num'] = $cnt['sub_num']?$cnt['sub_num']:0;
			$row['com_num'] = $cnt['sub_num']?$cnt['sub_num']:0;
			$row['att_num'] = $cnt['sub_num']?$cnt['sub_num']:0;
			MemRow::mset($key,$row);
		}
		return $row;
	}
	/**
	 * 获取用户的相关统计信息
	 *
	 * @param unknown_type $uid
	 */
	public function getCountByUid($uid,$flush = false){
		$key = USER_CNT_KEY.$uid;
		if(!($row = MemRow::getCache($key)) || $flush==true){
			$fav_num = $this->db->fetchField("SELECT COUNT(id) AS num FROM cartoon_collect WHERE uid = $uid",'num');
			$com_num = $this->db->fetchField("SELECT COUNT(id) AS num FROM app_com_post WHERE author_id = $uid  AND type = 1",'num');
			$att_num = $this->db->fetchField("SELECT COUNT(id) AS num FROM cartoon_attention WHERE uid = $uid",'num');
			$att_subscribe = $this->db->fetchField("SELECT COUNT(id) as num FROM cartoon_subscribe WHERE uid = $uid",'num');
			$row = array('fav_num' => $fav_num?$fav_num:0,'com_num' => $com_num?$com_num:0,'att_num'=>$att_num?$att_num:0,'sub_num'=>$att_subscribe?$att_subscribe:0);
			MemRow::mset($key,$row);
		}

		return $row;
	}
	
	/**
	 * 获取关注的列表
	 *
	 * @param unknown_type $uid
	 * @param unknown_type $page
	 * @param unknown_type $pageSize
	 * @return unknown
	 */
	public function getAttList($uid,$page=1,$pageSize = 15){
		if(!$uid) return false;
		$sql = "SELECT c_uid AS uid FROM cartoon_attention WHERE uid = $uid";
		
		return $this->db->selectPage($sql,array(),$page,$pageSize);
	}
	
	/**
	 * 根据用户名获取用户信息
	 * Enter description here ...
	 * @param unknown_type $name
	 */
	public function getUserByName($name,$field = array()){
		if(!$name) return false;
		if($rs = $this->db->fetchRow("SELECT * FROM $this->table WHERE username = '$name' ")){
			return $this->getInfoFields($rs,$field);
		}
	}
	
	
	/**
	 * 根据邮箱，获取用户信息
	 *
	 * @param unknown_type $email
	 * @return unknown
	 */
	public function getUserByEmail($email,$field = array()){
		if(!$email) return false;
		if($rs =  $this->db->fetchRow("SELECT * FROM $this->table WHERE email = '$email' ")){
			return $this->getInfoFields($rs,$field);
		}
		return false;
	}
	
	/**
	 * 设置用户状态
	 *
	 * @param unknown_type $uid
	 */
	public function setUserFlag($uid,$flag=FLAG_NORMAL){
		$uid = is_array($uid)?$uid:explode(',',$uid);
		//更改状态
		$sql = "UPDATE $this->table  SET  flag = $flag  WHERE uid IN (".implode(',',$uid) .")";
		if($this->db->query($sql)){
			if($flag == 2){//如果是管理员
				$sql = "INSERT INTO _users SELECT id,username FROM $this->table WHERE id IN (".implode(',',$uid) .")";
				$this->db->query("$sql");
			}
			/*foreach ($uid as $u){				
				$this->getUserByUid($u,true);
			}*/
			return true;
		}else return true;
	}
	
	/**
	 * 检查找回密码的
	 *
	 * @param unknown_type $args
	 */
	public function chkMail($email){
		$ret = array();
		if(!$email){
			return array('result'=>false,'reson'=>Error::ERROR_WRONG_PARAMS );
		}
		$sql = "SELECT * FROM cartoon_findpwd WHERE email = '".$email.'\'';
		if($rs = $this->db->fetchRow($sql)){
			if(intval(CURRENT_TIME - intval($rs['dateline']))>EXPIRE_PWD){
				//过期了
				return array('result'=>false,'reson'=>Error::ERROR_EXPIRE );
			}
			return array('result'=>true,'data'=>$rs);
		}
		return array('result'=>false,'reson'=>Error::ERROR_RECORD_NOT_FOUND  );		
	}
	
	/**
	 * 添加找回密码记录
	 *
	 * @param unknown_type $email
	 * @return unknown
	 */
	public function addFindPwdLog($email){
		if(!$email) return Error::ERROR_WRONG_PARAMS ;
		$this->delPwdLog($email);
		$para = array('email'=>$email,'dateline'=>CURRENT_TIME,'flag'=>0);
		return $this->db->insert('cartoon_findpwd',$para);
	}
	/**
	 * 删除找回密码记录
	 *
	 * @param unknown_type $email
	 * @return unknown
	 */
	public function delPwdLog($email){
		return $this->db->query("FROM cartoon_findpwd WHERE email =' $email'");
	}
	
	/**
	 * 按字段获取数据
	 *
	 * @param unknown_type $data
	 * @param unknown_type $field
	 * @return unknown
	 */
	private function getInfoFields(&$data,$field = array()){
		$return = array();
		if(!empty($field)){
			$field = (array)$field;
			foreach ($field as $v){
				$return[$v] = $data[$v];
			}
			return $return;
		}
		return $data;
	}
}